package ffmpeg;


import enums.Opt;
import file.FileOperating;
import file.Pid;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ProcessManage {

    public String getFfmpegPath() {
        return ffmpegPath;
    }

    public void setFfmpegPath(String ffmpegPath) {
        this.ffmpegPath = ffmpegPath;
    }

    public String getFfprobePath() {
        return ffprobePath;
    }

    public void setFfprobePath(String ffprobePath) {
        this.ffprobePath = ffprobePath;
    }

    private String ffmpegPath;

    private String ffprobePath;

    private FFmpeg fFmpeg;

    static {
        // kill 未关闭的推流进程
        String filePath = "/tmp/ffmpeg-push/pids.txt";
        List<String> pids = null;
        try {
            pids = FileOperating.readFile(filePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Pid.killPids(pids);
        // 删除pids.txt文件
        new File(filePath).delete();
    }

    /**
     * 用来初始化杀死残留的ffmpeg进程
     */
    public ProcessManage(){}

    public ProcessManage(String ffmpegPath, String ffprobePath) {
        this.ffmpegPath = ffmpegPath;
        this.ffprobePath = ffprobePath;
    }

    /**
     *
     * @param rtspUrl: rtsp://admin:12345asdf@192.168.4.64
     * @param ip: 127.0.0.1
     * @param rtmpPort: 1935
     * @param httpPort: 8000
     * @param timeMillis: 单位：毫秒 连接rtsp流地址最长时间
     * @return
     */
    public String push(String rtspUrl, String ip, Integer rtmpPort, Integer httpPort, long timeMillis) {
        fFmpeg = new FFmpeg(ffmpegPath, ffprobePath, rtspUrl, ip, rtmpPort, httpPort, timeMillis);
        fFmpeg.run();
        return String.valueOf(fFmpeg.getId());
    }

    public void stop(String id) {
        ProcessMap.destroy(Integer.parseInt(id));
    }

    public List<String> list() {
        List<String> list = new ArrayList<>();
        ProcessMap.processManagerHashMap.forEach((k,v) -> list.add(String.valueOf(k)));
        return list;
    }

    public String get(String id, Opt opt) {
        FFmpeg fFmpeg = ProcessMap.processManagerHashMap.get(Integer.parseInt(id));
        if (opt.ordinal() == 0) {
            return fFmpeg.getRtmpUrl();
        }
        if (opt.ordinal() == 1) {
            return fFmpeg.getHttpUrl();
        }
        if (opt.ordinal() == 2) {
            return fFmpeg.getPid();
        }
        return null;
    }

}
